package com.op.teachingliteapp.fragment.smartpan;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import Decoder.BASE64Decoder;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.op.teachingliteapp.R;
import com.op.teachingliteapp.bean.FileBean;
import com.op.teachingliteapp.common.BaseApp;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.common.api.ApiConstant;
import com.op.teachingliteapp.common.api.smartpan.CmdForm;
import com.op.teachingliteapp.common.api.smartpan.EntityBean;
import com.op.teachingliteapp.util.DirUtils;
import com.op.teachingliteapp.util.FileUtils;
import com.op.teachingliteapp.util.SharedPreferenceUtil;
import com.op.teachingliteapp.util.ToastUtils;
import com.op.teachingliteapp.util.asynctask.HttpPostTask;
import com.op.teachingliteapp.util.asynctask.OnTaskProcessListener;

/**
 * Created by 陈宇瀚 on 2015/7/14.
 * 
 */
@SuppressLint("ResourceAsColor")
public class SmartPanListviewAdapter extends BaseAdapter {
	private Context context;
	private List<FileBean> list;

	public SmartPanListviewAdapter(Context context, List<FileBean> list) {
		this.context = context;
		this.list = list;

	}

	public void setList(List<FileBean> list) {
		this.list = list;
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public String getFileSize(int position) {
		return list.get(position).getSize();
	}

	public String getFileName(int position) {
		return list.get(position).getName();
	}

	public boolean isFile(int position) {
		return list.get(position).isFile();
	}

	@SuppressLint("ResourceAsColor")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		Log.i("SmartPanListviewAdapter", "" + list.size());
		ViewHolder viewHolder;
		if (null == convertView) {
			viewHolder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(R.layout.item_smart_pan, null);
			viewHolder.mySmartPanFileChoose = (CheckBox) convertView.findViewById(R.id.my_smart_file_choose);
			viewHolder.mySmartPanFileName = (TextView) convertView.findViewById(R.id.my_smart_pan_item_file_name);
			viewHolder.mySmartPanFileDelete = (ImageButton) convertView.findViewById(R.id.my_smart_pan_item_file_delete);
			viewHolder.mySmartPanFileDown = (ImageButton) convertView.findViewById(R.id.my_smart_pan_item_file_down);
			viewHolder.mySmartPanFileType = (ImageView) convertView.findViewById(R.id.my_smart_pan_file_type);
			viewHolder.mySmartPanFileTime = (TextView) convertView.findViewById(R.id.my_smart_pan_item_file_time);
			viewHolder.mySmartPanFileSize = (TextView) convertView.findViewById(R.id.file_size);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		// 判断与云盘的文件是否对应
		if (list.get(position).getCondition().equals("HAVA")) {
			viewHolder.mySmartPanFileName.setTextColor(Color.GRAY);
		} else if (list.get(position).getCondition().equals("SmartNO")) {
			viewHolder.mySmartPanFileName.setTextColor(Color.RED);
		} else if (list.get(position).getCondition().equals("ThisNO")) {
			viewHolder.mySmartPanFileDelete.setVisibility(View.INVISIBLE);
			viewHolder.mySmartPanFileName.setTextColor(Color.BLUE);
		} else {
			viewHolder.mySmartPanFileName.setTextColor(Color.GRAY);
		}
		// 判断是否是文件
		if (list.get(position).isFile()) {
			String size = "";
			try{
				size = convertFileSize(Long.parseLong(list.get(position).getSize()));
			}catch(Exception e){
				size = list.get(position).getSize();
			}
			
			viewHolder.mySmartPanFileSize.setText(size);
			viewHolder.mySmartPanFileType.setBackgroundResource(R.drawable.file);
			// viewHolder.mySmartPanFileChoose.setVisibility(View.INVISIBLE);
		} else {
			viewHolder.mySmartPanFileSize.setText("");
			// Log.i("xxx", list.get(position).getPath());
			viewHolder.mySmartPanFileType.setBackgroundResource(R.drawable.folder);
		}

		viewHolder.mySmartPanFileName.setText(list.get(position).getName());
		viewHolder.mySmartPanFileTime.setText(list.get(position).getUpdated());
		// 删除按钮监听
		viewHolder.mySmartPanFileDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final String fileName = list.get(position).getName();
				new AlertDialog.Builder(context).setTitle("提示").setMessage("确定删除该文件夹 : " + fileName).setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String ownerId = SharedPreferenceUtil.getInstance(context).getString(Common.Prefs.USER_ID, "");
						String path = list.get(position).getPath();
						path = path.substring(0, path.lastIndexOf("/")).replace("/data/data/com.op.teachingliteapp/files/user-" + ownerId, "");

						Log.i("-----", path + "/" + fileName);

						// path后如果没有"/",记得加"/"
						String cmdJson = CmdForm.generateJsonCmd(ownerId, path + "/" + fileName, CmdForm.CMD_DELETE_FOLDER);
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("CMD", cmdJson));
						HttpPostTask task = new HttpPostTask(context, ApiConstant.SMART_PAN_URL, params);
						task.setTaskListener(new OnTaskProcessListener() {
							@Override
							public void prepare() {
							}

							@Override
							public void completed(String result) {

								Log.i("-----", result);
								String msg = CmdForm.getOutputMessage(result);
								FileUtils.deleteFile(list.get(position).getPath());
								list.remove(position);
								notifyDataSetChanged();
								ToastUtils.show(context, "文件删除成功");
								synRefresh();
								// if (msg.equals("sucess delete path")) {
								// FileUtils.deleteFile(list.get(position).getPath());
								// list.remove(position);
								// notifyDataSetChanged();
								// ToastUtils.show(context, "文件删除成功");
								// } else {
								// ToastUtils.show(context, "文件删除失败");
								// }
							}

						});
						task.execute();
					}
				}).show();
			}
		});

		// 下载按钮监听
		viewHolder.mySmartPanFileDown.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String ownerId = SharedPreferenceUtil.getInstance(context).getString(Common.Prefs.USER_ID, "");
				String path = list.get(position).getPath();
				final String localPath = path.substring(0, path.lastIndexOf("/"));
				String remotePath = localPath.replace("/data/data/com.op.teachingliteapp/files/user-" + ownerId, "");
				final String fileName = list.get(position).getName();

				Log.i("-----", localPath);
				Log.i("-----", fileName);
				Log.i("-----", localPath + "/" + fileName);


				// path后如果没有"/",记得加"/"
				String cmdJson = CmdForm.generateJsonCmd(ownerId, remotePath + "/" + fileName, CmdForm.CMD_DOWNLOAD);
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("CMD", cmdJson));
				HttpPostTask task = new HttpPostTask(context, ApiConstant.SMART_PAN_URL, params);
				task.setTaskListener(new OnTaskProcessListener() {
					@Override
					public void prepare() {
					}

					@Override
					public void completed(String result) {
						Log.i("-----", result);
						byte[] resultByteArray = result.getBytes();
						FileUtils.saveByteArrayToFile(localPath + "/" + fileName, resultByteArray);
						synRefresh();
					}

				});
				task.execute();
			}
		});

		return convertView;
	}

	@SuppressWarnings("unused")
	private class ViewHolder {
		// 每个item的各种控件
		private CheckBox mySmartPanFileChoose;
		private ImageView mySmartPanFileType;
		private TextView mySmartPanFileName;
		private TextView mySmartPanFileTime;
		private TextView mySmartPanFileSize;
		private ImageButton mySmartPanFileDown, mySmartPanFileDelete;
	}

	/**
	 * byte(字节)根据长度转成kb和mb和gb
	 * 
	 * @param bytes
	 * @return
	 */
	public static String convertFileSize(long size) {
		long kb = 1024;
		long mb = kb * 1024;
		long gb = mb * 1024;

		if (size >= gb) {
			return String.format("%.1f GB", (float) size / gb);
		} else if (size >= mb) {
			float f = (float) size / mb;
			return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
		} else if (size >= kb) {
			float f = (float) size / kb;
			return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
		} else
			return String.format("%d B", size);
	}

	/**
	 * 强制同步刷新
	 */
	public void synRefresh() {
		String ownerId = SharedPreferenceUtil.getInstance(context).getString(Common.Prefs.USER_ID, "");
		String path = list.get(0).getPath();
		Log.i("xxxxxxxxxxxxxx", "" + path);
		path = path.replace("/data/data/com.op.teachingliteapp/files/user-" + ownerId, "");;
		path = path.substring(0, path.lastIndexOf("/"));
		String cmdJson = CmdForm.generateJsonCmd(ownerId, path, CmdForm.CMD_LIST);
		Log.i("xxxxxxxxxxxxxx", "" + path);
		// 发送POST请求给ApiConstant.SMART_PAN_URL
		getPostResult(cmdJson);
	}

	public void getPostResult(String cmdJson) {
		// 做异步请求
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("CMD", cmdJson));
		HttpPostTask task = new HttpPostTask(context, ApiConstant.SMART_PAN_URL, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				Log.i("SmartPanFragment", "同步返回数据: " + result);

				List<EntityBean> entityBeanList = new ArrayList<EntityBean>();
				if (CmdForm.fillEntityBeanList(entityBeanList, result)) {
					System.out.println("获取到的Size为: " + entityBeanList.size());
				} else {
					System.out.println("路径有问题");
				}

				// 本地数据库与云盘对比
				for (int i = 0; i < list.size(); i++) {
					for (int j = 0; j < entityBeanList.size(); j++) {
						if (list.get(i).getName().equals(entityBeanList.get(j).getEntityName())) {
							list.get(i).setCondition("HAVA");
							Log.i("SmartPanFragment", "云盘:" + entityBeanList.get(j).getEntityName() + "本地:" + list.get(i).getName());
						}
					}
					Log.i("SmartPanFragment", list.get(i).getName() + ":" + list.get(i).getCondition());
					// 如果不等，则说明本地Bean内包含网络上不存在的Bean
					if (list.get(i).getCondition() == null || !list.get(i).getCondition().equals("HAVA")) {
						list.get(i).setCondition("SmartNO");
					}
					// Log.i("SmartPanFragment", "对比本地与云盘:" +
					// fileBean.get(i).getName());
				}
				// 云盘与本地对比
				for (int i = 0; i < entityBeanList.size(); i++) {
					for (int j = 0; j < list.size(); j++) {
						if (entityBeanList.get(i).getEntityName().equals(list.get(j).getName())) {
							entityBeanList.get(i).setCondition("HAVA");
						}
					}
					// 如果不等，则说明云盘内包含本地不存在的Bean
					if (entityBeanList.get(i).getCondition() == null || !entityBeanList.get(i).getCondition().equals("HAVA")) {
						boolean isFile;
						FileBean addFileBean = new FileBean();
						addFileBean.setCondition("ThisNO");
						addFileBean.setName(entityBeanList.get(i).entityName);
						addFileBean.setSize(entityBeanList.get(i).getFileSize());
						addFileBean.setPath(list.get(list.size() - 1).getPath());
						// 判断是否是文件
						if (entityBeanList.get(i).getEntityType().equals(EntityBean.TYPE_FILE)) {
							isFile = true;

						} else {
							isFile = false;
							Log.i("SmartPanFragment", "" + addFileBean.getName());
							createFolders(addFileBean);
						}
						addFileBean.setFile(isFile);

						list.add(addFileBean);
						setList(list);
						notifyDataSetChanged();
					}
				}
			}

		});
		task.execute();
	}

	/**
	 * 创建 相应课程的文件夹
	 * 
	 * @param userId
	 * @param list
	 */
	public void createFolders(FileBean fileBean) {
		SharedPreferences preferences = SharedPreferenceUtil.getInstance(BaseApp.getAppContext());
		String currentUserId = preferences.getString(Common.Prefs.USER_ID, "");
		DirUtils dirUtils = new DirUtils(context, currentUserId);
		List<String> courses = new ArrayList<String>();
		courses.add(fileBean.getName());
		// Log.i("SmartPan", "" + fileBean.getPath().substring(0,
		// fileBean.getPath().lastIndexOf("/")));
		dirUtils.createDirs(courses, fileBean.getPath().substring(0, fileBean.getPath().lastIndexOf("/")));
	}

}
